// 已平台发货
var tblConsigned;
// 高级检索条件
var searchCondition = {
    "cons" : "",
    "consTel" : "",
    "shopId" : "",
    "paidDateStart" : "",
    "paidDateEnd" : "",
    "lgstNo" : "",
    "storId" : "",
    "goodsCode" : "",
    "goodsName" : "",
    "skuCode" : "",
    "skuName" : ""
};

$(document).ready(function() {
    $('.panel-default .datetimepicker-default').datetimepicker();

    // 构建店铺下拉列表
    $.ajax({
        type : "GET",
        url : "/shop/unpagedShopList.action?prjId=" + window.top.window.$("#projectSwitch").val(),
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        async : true,
        success : function(data) {
            if (data.result == "success") {
                $("#shopId option").remove();
                $("#shopId").append("<option value=''>请选择</option>");
                $.each(data.data, function(n, value) {
                    $('#shopId').append("<option value='" + value.shopId + "'>" + value.shopName + "</option>");
                });
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });

    // 构建第三方仓库下拉列表
    $.ajax({
        type : "GET",
        url : "/stor/storList.action?length=-1",
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        data : {
            storType : "cainiao"
        },
        async : true,
        success : function(data) {
            if (data.result == "success") {
                $("#storId option").remove();
                $("#storId").append("<option value=''>请选择</option>");
                $.each(data.data, function(n, value) {
                    $('#storId').append("<option value='" + value.storId + "'>" + value.storName + "</option>");
                });
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });

    getConsigned();

});

// 设置高级查询条件
function setSearchCondition() {
    // 设置高级查询条件
    searchCondition = {
        "cons" : encodeURI($('#cons').val()),
        "consMobile" : encodeURI($('#consMobile').val()),
        "shopId" : encodeURI($('#shopId').val()),
        "paidDateStart" : encodeURI($('#paidDateStart').val()),
        "paidDateEnd" : encodeURI($('#paidDateEnd').val()),
        "lgstNo" : encodeURI($('#lgstNo').val()),
        "storId" : encodeURI($('#storId').val()),
        "goodsCode" : encodeURI($('#goodsCode').val()),
        "goodsName" : encodeURI($('#goodsName').val()),
        "skuCode" : encodeURI($('#skuCode').val()),
        "skuName" : encodeURI($('#skuName').val())
    };
}

// 快速查询回车
$('#quickSearch').keydown(function(e) {
    if (e.keyCode == 13 && $('#btnQuickSearch').is(":visible")) {
        $('#btnQuickSearch').click();
    }
});

// 快速查询按钮
$("#btnQuickSearch").click(function() {
    setSearchCondition();
    drawTable();
});

// 高级查询按钮
$("#advSearchSubmit").click(function() {
    setHidValue("frmAdvSearch");
    setSearchCondition();
    drawTable();
});

// 重置按钮
$("#advSearchReset").click(function() {
});

// 隐藏高级查询
$("#advSearchPanel").hide();
$("#btnAdvSearch").click(function() {
    if ($("#advSearchPanel").is(":hidden")) {
        $("#advSearchPanel").show();
        $("#btnQuickSearch").hide();
        $(this).children("i:eq(0)").removeClass("fa-angle-double-down");
        $(this).children("i:eq(0)").addClass("fa-angle-double-up");
    } else {
        $("#advSearchPanel").hide();
        $("#btnQuickSearch").show();
        $(this).children("i:eq(0)").removeClass("fa-angle-double-up");
        $(this).children("i:eq(0)").addClass("fa-angle-double-down");
    }
});

// tab显示时
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    var tables = $.fn.dataTable.tables({
        visible : true,
        api : true
    });
    if (tables.length > 0) {
        $(tables).DataTable().columns.adjust();
    }
    $(tables).find("th.sorting_asc").removeClass("sorting_asc");
});

// 已平台发货列表
function getConsigned() {
    if (tblConsigned != null && tblConsigned != undefined && "" != tblConsigned) {
        tblConsigned.draw();
        return;
    }

    tblConsigned = $('#tblConsigned').DataTable(
            {
                "processing" : true,
                "serverSide" : true,
                "lengthMenu" : [ [ 10, 25, 50, 100, 500, 1000 ], [ 10, 25, 50, 100, 500, 1000 ] ],
                "dom" : '<"bottom"rtflp>',
                "searching" : false,
                "scrollX" : true,
                "scrollCollapse" : true,
                "pagingType" : "full_numbers",
                "deferRender" : true,
                "ajax" : {
                    "url" : "/cainiaoshiporder/getShiporderList.action",
                    "data" : function(d) {
                        d.quickSearch = encodeURI($('#quickSearch').val());
                        d.formJson = JSON.stringify(searchCondition);
                    }
                },
                "tableTools" : {
                    "sRowSelect" : "bootstrap"
                },
                "columns" : [
                        {
                            "data" : "skuShow",
                            "orderable" : false
                        },
                        {
                            "data" : "lockStatus",
                            "render" : function(data, type, row, meta) {
                                if (row.lockStatus == "y") {
                                    return '<span class="glyphicon glyphicon-lock"></span>';
                                } else {
                                    return "&nbsp;";
                                }
                            }
                        },
                        {
                            "data" : "shiporderCode"
                        },
                        {
                            "data" : "wmsShiporderCode"
                        },
                        {
                            "data" : "sourceCode",
                            "render" : function(data, type, row, meta) {
                                var htmlName = "";
                                if (row.sourceType == "or") {
                                    htmlName = "orderList.html";
                                } else {
                                    htmlName = "afterSaleResend.html";
                                }
                                return '<a href="#" style="text-decoration:underline;" onclick="changeMenu(\'' + row.sourceCode + '\',\''
                                        + htmlName + '\');">' + row.sourceCode + '</a>';
                            },
                        }, {
                            "data" : "tradeCode"
                        }, {
                            "data" : "sourceType",
                            "render" : function(data, type, row, meta) {
                                if (row.sourceType == "or") {
                                    return "订单发货";
                                } else {
                                    return "补发发货";
                                }
                            }
                        }, {
                            "data" : "shopName"
                        }, {
                            "data" : "buyerNick"
                        }, {
                            "data" : "createTime"
                        }, {
                            "data" : "paidDate"
                        }, {
                            "data" : "consignTime"
                        } ],
                "columnDefs" : [ {
                    "className" : "truncate-text tooltip-column-detail",
                    "targets" : [ 1 ]
                }, {
                    "className" : "truncate-text tooltip-column-detail",
                    "targets" : [ 2 ]
                }, {
                    "className" : "truncate-text tooltip-column-detail",
                    "targets" : [ 3 ]
                }, {
                    "className" : "truncate-text tooltip-column-detail",
                    "targets" : [ 4 ]
                }, {
                    "className" : "truncate-text tooltip-column-detail",
                    "targets" : [ 5 ]
                }, {
                    "className" : "truncate-text tooltip-column-detail",
                    "targets" : [ 6 ]
                }, {
                    "className" : "truncate-text tooltip-column-detail",
                    "targets" : [ 7 ]
                }, {
                    "className" : "truncate-text tooltip-column-detail",
                    "targets" : [ 8 ]
                }, {
                    "className" : "truncate-text tooltip-column-detail",
                    "targets" : [ 9 ]
                }, {
                    "className" : "truncate-text tooltip-column-detail",
                    "targets" : [ 10 ]
                }, {
                    "className" : "truncate-text tooltip-column-detail",
                    "targets" : [ 11 ]
                }, ],
                "order" : [ [ 10, "desc" ] ]
            });

    // 文字过长截断显示悬浮框
    $("#tblConsigned").tooltip({
        selector : ".tooltip-column-detail",
        container : "body",
        title : function() {
            if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                return $(this).text();
            }
        }
    });

}

// 子表格显示隐藏
$('.tablefirst tbody')
        .on(
                'click',
                'td .sku-show',
                function() {
                    var shiporderId = $(this).attr('shiporderId');
                    var tr = $(this).closest('tr');
                    var table;
                    var row;
                    var tablename = "";
                    table = tblConsigned;
                    row = tblConsigned.row(tr);
                    tablename = "tblConsigned";
                    // 加载过，而且是显示的状态
                    if (row.child.isShown()) {
                        row.child.hide();
                        tr.removeClass('shown');
                        $(this).removeClass('fa-chevron-up');
                        $(this).addClass('fa-chevron-down');
                    } else {
                        // 关闭其他
                        $('#' + tablename + ' tbody tr').each(function() {
                            if ($(this).attr("role") == "row") {
                                table.row($(this)).child.hide();
                            }
                        });
                        $('.fa-chevron-up').addClass('fa-chevron-down');
                        $('.fa-chevron-down').removeClass('fa-chevron-up');

                        var temp = '<iframe id="contentFrame" name="contentFrame" style="width:100%;" frameborder="0" scrolling="auto" src="/views/ext/cainiao/shiporder/sonShiporderList.html" width="100%" height="245"></iframe>';
                        row.child(temp).show();
                        tr.addClass('shown');
                        $(this).addClass('fa-chevron-up');
                        $(this).removeClass('fa-chevron-down');

                        $('#shiporderId').val(shiporderId);
                    }
                });

// 导出
function exportShiporder() {
}

//改变菜单选中状态
function changeMenu(sourceCode, htmlName) {
    window.top.window.$('a').each(function() {
        var str = $(this).attr("onclick");
        if (str != undefined && str.indexOf(htmlName) > 0) {
            window.top.window.$("#orderCode").val(sourceCode);
            $(this).parents(':eq(2)').children('a').get(0).click();
            $(this).click();
            if (window.top.window.getIframeByTabName("系统补发单").contentWindow.document.body.innerHTML != "") { // 页面已经打开过
                window.top.window.refreshTabByTabName("系统补发单");
            }
            return false;
        }
    });
}


//刷新高级查询和快速查询
function refreshCheck() {
    $('#quickSearch').val("");
    $("#advSearchReset").click();
    searchCondition = {};
    if (!$("#advSearchPanel").is(":hidden")) {
        $("#btnAdvSearch").click();
    }
}

//重画表格
function drawTable() {
    tblConsigned.draw();
}